import { request, baseUrl } from "../../utils/request";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: "", //头像地址
    nickName: "微信用户", //昵称
    id: 0 //用户id
  },

  /**
   * 处理头像选择事件
   */
  onChooseAvatar(e) {
    //获取图片的临时地址
    const { avatarUrl } = e.detail
    //上传图片至服务器
    wx.uploadFile({
      url: baseUrl + "/wx/user/upload",
      filePath: avatarUrl,
      name: "picFile",
      header: {
        "Authorization": wx.getStorageSync("user").token
      },
      success: (res) => {
        //转JSON对象
        const resultData = JSON.parse(res.data)
        if (resultData.state === 0) {
          this.setData({
            avatarUrl: resultData.data
          })
        }
      }
    })
  },

  /**
   * 处理提交
   */
  async handlerFormSubmit(e) {
    //获取头像路径
    const avatarUrl = this.data.avatarUrl
    if (!avatarUrl || avatarUrl.length === 0) {
      wx.showToast({ title: "请上传头像", icon: "none" });
      return;
    }
    //获取昵称输入框的文字内容
    const nickName = e.detail.value.nickname
    if (!nickName || nickName.length > 10) {
      wx.showToast({ title: "收件人姓名不少于1个字，最多10个", icon: "none" });
      return;
    }
    const requestData = { avatarUrl, nickName }
    const user = wx.getStorageSync("user")
    //发送修改请求
    const res = await request({ url: "/wx/user/update", method: "POST", data: requestData, header: { "Authorization": user.token } })
    if (res.data.state === 0) {
      wx.showToast({
        title: "更新成功",
        mask: true,
        success: () => {
          setTimeout(() => {
            //更新数据
            this.setData({
              avatarUrl,
              nickName
            })
            //更新本地用户缓存
            user.avatarUrl = avatarUrl
            user.nickName = nickName
            wx.setStorageSync("user", user)
            //跳回到上一个页面
            wx.navigateBack({
              delta: 1
            })
          }, 1500)
        }
      })
    } else {
      wx.showToast({ title: res.data.message, icon: "none" });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const user = wx.getStorageSync("user")
    if (user) {
      this.setData({
        id: user.id,
        avatarUrl: user.avatarUrl,
        nickName: user.nickName
      })
    }
  }
})